import Router = require('koa-router')
import { File } from 'formidable'
import * as path from 'path'
import * as fse from 'fs-extra'

const router = new Router({
  prefix: '/api/file'
})

router.post('/upload', async ctx => {
  const file = Object.values(ctx.request.files)[0] as File

  const filename = Date.now().toString() + file.name
  const dest = path.join(__dirname, '../../public/upload', filename)

  await fse.move(file.path, dest) // 移动文件
  const Path = dest.split('public')[1].replaceAll('\\', '/')
  ctx.body = {
    stat: 'OK',
    url: Path
  }
})

export default router
